import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'
import register from '../views/register.vue'
import layout from '../views/layout.vue'
import detail from '../views/detail.vue'
import article from '../views/article.vue'
import collect from '../views/collect.vue'
import like from '../views/like.vue'
import user from '../views/user.vue'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: login },
  { path: '/register', component: register },
  { path: '/detail/:id', component: detail },
  {
    path: '/',
    component: layout,
    redirect: '/article',
    children: [
      { path: '/article', component: article },
      { path: '/collect', component: collect },
      { path: '/like', component: like },
      { path: '/user', component: user }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 取到 token
  const token = getToken()
  // 判断 有没有token
  if (token) {
    // 有 token 直接放行
    next()
  } else {
    // 没有 token 判断访问的页面在不在白名单
    if (whiteList.includes(to.path)) {
      // 在白名单放行
      next()
    } else {
      // 不在直接跳转到首页
      next('/login')
    }
  }
})

export default router
